<template>
  <div class="vip-account-config">
    <div v-loading="loading" class="app-main-content-box">
      <!-- 标题 -->
      <div class="flex-x-start-center">
        <app-main-title title="储值设置" :margin-bottom="0" />
        <el-button-group style="margin-left: 30px">
          <el-button
            size="small"
            round
            @click="initData()"
          >取消
          </el-button>
          <el-button
            type="primary"
            size="small"
            round
            @click="onSubmit('form')"
          >保存
          </el-button>
        </el-button-group>
      </div>
      <div style="margin-top: 20px;">
        启用储值：
        <el-switch v-model="form.enableRecharge" :disabled="isEnableRecharge" />
      </div>

      <!-- 储值表单 -->
      <div class="form">
        <el-form ref="form" :model="form" :rules="rules" label-width="160px" size="small">
          <el-collapse-transition>
            <div v-if="form.enableRecharge">
              <!-- 充值规则卡片 -->
              <el-card class="top-card">
                <app-main-sub-title title="充值规则" />
                <el-form-item label="可选储值金额：">
                  <div
                    v-for="(item,index) in form.defaultAmount"
                    :key="index"
                    class="default-account-val app-border-color-primary"
                  >
                    <span>{{ item/100 }}元</span>
                    <i class="el-icon-close" @click="delDefaultAccount(index)" />
                  </div>
                  <el-button
                    type="primary"
                    icon="el-icon-plus"
                    size="small"
                    circle
                    @click="addGiveBalance"
                  />
                  <div v-if="rechargeTips" class="recharge-tips app-text-color-danger">请至少设置一种储值方式</div>
                  <div
                    v-if="minAmountTips"
                    class="recharge-tips app-text-color-danger"
                  >可选储值最小金额不能大于最低充值金额</div>
                </el-form-item>
                <el-form-item label="可充值任意金额：">
                  <el-switch v-model="form.allowAnyAmount" />
                  <el-form-item v-if="form.allowAnyAmount" prop="minAmount" style="margin-bottom:0">
                    <el-checkbox v-model="isEnableMinAmount">最低需要充值&nbsp;</el-checkbox>
                    <el-input
                      v-model.trim="form.minAmount"
                      :disabled="!isEnableMinAmount"
                      maxlength="10"
                      style="width:200px"
                    >
                      <template slot="append">元</template>
                    </el-input>
                  </el-form-item>
                  <div v-if="rechargeTips" class="recharge-tips app-text-color-danger">请至少设置一种储值方式</div>
                </el-form-item>
                <el-form-item label="充值后冻结部分金额：" >
                  <el-switch v-model="form.enableLockBalance" disabled />
                  <el-button
                    v-if="form.enableLockBalance"
                    size="mini"
                    type="text"
                    @click="openDialogLockRule"
                  >修改冻结规则</el-button>
                  <div
                    v-if="form.enableLockBalance&&form.balanceLockDays&&form.balanceLockPercent "
                    class="lock-tips"
                  >
                    顾客充值后&nbsp;
                    <span style="color: red">{{ form.balanceLockDays }}</span>&nbsp;天内冻结本次充值所得实充金额的&nbsp;
                    <span style="color: red">{{ form.balanceLockPercent }}%</span>
                  </div>
                  <div
                    v-if="form.enableLockBalance&&form.frozenGivenDays&& form.frozenGivenPercent"
                    class="lock-tips"
                  >
                    顾客充值后&nbsp;
                    <span style="color: red">{{ form.frozenGivenDays }}</span>&nbsp;天内冻结本次充值所得赠送金额的&nbsp;
                    <span style="color: red">{{ form.frozenGivenPercent }}%</span>
                  </div>
                  <div v-if="lockTips" class="recharge-tips app-text-color-danger">请至少设置一种冻结规则</div>
                </el-form-item>
                <el-form-item label="余额支付时同享优惠：">
                  <el-switch v-model="form.balanceCanDiscount" />
                </el-form-item>
                <el-form-item label="线上自助充值：">
                  <el-switch v-model="form.enableOnlineRecharge" />
                </el-form-item>
                <el-form-item label="小额免密功能：">
                  <el-switch v-model="form.enableSkipPassword" />
                  <el-button
                    v-if="form.enableSkipPassword"
                    size="mini"
                    type="text"
                    @click="openDialogSkipPasswordAmount"
                  >修改小额免密金额</el-button>
                  <div v-if="form.enableSkipPassword" class="lock-tips">
                    单笔消费小于等于&nbsp;
                    <span style="color: red">{{ form.skipPasswordAmount/100 }}&nbsp;</span>元时无需输入支付密码
                  </div>
                </el-form-item>
                <el-form-item label="手机号消费免密扣款：">
                  <el-switch
                    v-model="form.phoneNeedPwd"
                    :active-value="false"
                    :inactive-value="true"
                  />
                </el-form-item>
                <el-form-item label="线下充值密码：">
                  <el-button size="mini" type="text" @click="openDialogRechargePsw">设置</el-button>
                </el-form-item>
                <el-form-item label="使用范围：" class="use-limit-box" prop="usedScopes">
                   <el-checkbox-group v-model="form.usedScopes">
                      <el-checkbox :label="1">小程序消费抵扣  
                        <el-tooltip class="item" effect="dark" content="小程序消费抵扣指用户可在小程序下单使用余额抵扣现金；" placement="top-start">
                          <i class="el-icon-question" />
                        </el-tooltip>
                    </el-checkbox>
                      <el-checkbox :label="2">扫码消费抵扣
                         <el-tooltip class="item" effect="dark" content="扫码消费抵扣指用户可在扫码商户码牌使用余额抵扣现金；" placement="top-start">
                            <i class="el-icon-question" />
                        </el-tooltip>
                      </el-checkbox>
                    </el-checkbox-group>
                    <div>注：必选中一项，未选中的场景表示用户不可在这种场景使用积分抵扣；</div>
                </el-form-item>
              </el-card>

              <!-- 账户扣减规则配置卡片  -->
              <el-card class="bottom-card">
                <div class="flexRBC">
                  <app-main-sub-title title="扣减规则" />
                  <el-button size="mini" type="text" @click="openDialogPayRule">修改</el-button>
                </div>
                <ul class="pay-rule">
                  <li v-if="form.payRule===1">
                    1.每笔余额支付实充账户扣除&nbsp;
                    <span style="color: red">{{ form.payBalancePercent }}%</span>&nbsp;，即赠送账户扣除&nbsp;
                    <span style="color: red">{{ 100-form.payBalancePercent }}%</span>
                  </li>
                  <li v-if="form.payRule===2">1.优先扣除实充账户</li>
                  <li v-if="form.payRule===3">1.优先扣除赠送账户</li>
                  <!-- <li v-if="form.onlyEnoughRecharge">2.实充账户余额不足不可以付款</li> -->
                </ul>
              </el-card>

              <!-- 账户扣减规则配置卡片  -->
              <el-card class="bottom-card">
                <app-main-sub-title title="储值清零规则" />
                <el-form-item label="赠送余额清零：" prop="clearType">
                  <el-select v-model="form.clearType" placeholder="请选择">
                    <el-option label="永久不清零" :value="0" />
                    <el-option label="定期清零上一年赠送余额" :value="1" />
                    <el-option label="定期清零上一月赠送余额" :value="2" />
                    <el-option label="定期清零上一周赠送余额" :value="3" />
                  </el-select>
                </el-form-item>
                <el-form-item v-if="form.clearType!=0" label="清零日期：" prop="clearDate">
                  <el-cascader
                    v-if="form.clearType==1"
                    v-model="form.clearDate"
                    placeholder="请选择日期"
                    :options="clearDateYearOptions"
                  />
                  <el-select v-if="form.clearType==2" v-model="form.clearDate" placeholder="请选择">
                    <el-option
                      v-for="item in 28"
                      :key="item"
                      :label="item+'号'"
                      :value="String(item)"
                    />
                  </el-select>
                  <el-select v-if="form.clearType==3" v-model="form.clearDate" placeholder="请选择">
                    <el-option
                      v-for="item in weekOptions"
                      :key="item.label"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>&nbsp;
                  <el-tag>清零任务将在配置日期的当天凌晨02:00执行</el-tag>
                </el-form-item>
              </el-card>
            </div>
          </el-collapse-transition>
        </el-form>
      </div>
    </div>

    <!-- 冻结规则弹框 -->
    <dialog-lock-rule ref="dialogLockRule" :config-form.sync="form" />
    <!-- 设置线下储值密码弹框 -->
    <dialog-recharge-psw ref="dialogRechargePsw" />
    <!-- 扣减规则弹框 -->
    <dialog-pay-rule ref="dialogPayRule" :config-form.sync="form" />
  </div>
</template>

<script>
import {
  validateCustomTwoDecimal,
  validateCustomPositiveInt,
  validatePositiveInt
} from '@/utils/validate.js'
import { getAccountRule, updateAccountRule } from '@/api/vip'
import DialogLockRule from './components/DialogLockRule.vue' // 冻结弹框
import DialogRechargePsw from './components/DialogRechargePsw.vue' // 储值密码弹框
import DialogPayRule from './components/DialogPayRule.vue' // 账户扣减规则
export default {
  components: {
    DialogLockRule,
    DialogRechargePsw,
    DialogPayRule
  },
  data() {
    /**
       * 表单校验方法相关
       */
    const validateMinAmount = (rule, value, callback) => {
      if (this.isEnableMinAmount) {
        if (value === '') {
          callback(new Error('请输入最小充值金额'))
        } else if (!validateCustomTwoDecimal(value, 4)) {
          callback(new Error('请输入0.01~9999.99范围金额（小数位不超过2位）'))
        } else {
          callback()
        }
      } else {
        callback()
      }
    }
    return {
      /**
         * 表单校验字段相关
         */
      rules: {
        minAmount: [
          {
            required: true,
            validator: validateMinAmount,
            trigger: ['blur']
          }
        ],
        clearType: [
          {
            required: true,
            message: '请选择清零类型',
            trigger: ['blur', 'change']
          }
        ],
        clearDate: [
          {
            required: true,
            message: '请选择清零日期',
            trigger: ['blur', 'change']
          }
        ],
        usedScopes: [
					{ type: 'array', required: true, message: '使用范围至少要选择一项', trigger: 'change' }
				],
      },
      // 配置
      day: [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31],
      clearDateYearOptions: [],
      weekOptions: [
        {
          label: '周一',
          value: '2'
        },
        {
          label: '周二',
          value: '3'
        },
        {
          label: '周三',
          value: '4'
        },
        {
          label: '周四',
          value: '5'
        },
        {
          label: '周五',
          value: '6'
        },
        {
          label: '周六',
          value: '7'
        },
        {
          label: '周日',
          value: '1'
        }
      ],
      // 状态
      loading: false,
      minAmountTips: false,
      rechargeTips: false,
      lockTips: false,
      // 数据
      isEnableRecharge: false,
      isEnableMinAmount: false,
      form: {
        enableRecharge: true,
        defaultAmount: [], // 可以赠送的余额
        allowAnyAmount: false, // 可充值任意金额
        minAmount: '', // 最小充值金额
        enableLockBalance: false, // 充值后冻结部分金额
        balanceLockPercent: 0, // 冻结比例
        balanceLockDays: 0, // 冻结天数
        frozenGivenPercent: 0, // 冻结比例
        frozenGivenDays: 0, // 冻结天数
        phoneNeedPwd: true,
        onlyEnoughRecharge: false,
        balanceCanDiscount: false,
        enableOnlineRecharge: false,
        payBalancePercent: null,
        payRule: null,
        enableSkipPassword: true,
        skipPasswordAmount: 0,
        clearDate: null,
        clearType: 0,
        givenClear: false,
        usedScopes:[]
      },
      checkList:''
    }
  },
  watch: {
    form: {
      handler: function(val) {
        if (val.enableRecharge) {
          // 必须设置一种储值金额
          if (!val.allowAnyAmount && val.defaultAmount.length === 0) {
            this.rechargeTips = true
          } else {
            this.rechargeTips = false
          }
          // 校验冻结规则
          if (val.enableLockBalance) {
            this.lockTips =
                !((validatePositiveInt(val.balanceLockDays) &&
                  validateCustomPositiveInt(val.balanceLockPercent, 2, [
                    100,
                    '100'
                  ])) ||
                (validatePositiveInt(val.frozenGivenDays) &&
                  validateCustomPositiveInt(val.frozenGivenPercent, 2, [
                    100,
                    '100'
                  ])))
          } else {
            this.lockTips = false
          }
        }
        this.findIsTrueMinAmount()
      },
      deep: true
    },
    isEnableMinAmount(val) {
      // 判断最小金额 与 默认可选最小金额
      if (!val) {
        this.$refs.form.clearValidate(['minAmount'])
      }
      this.findIsTrueMinAmount()
    },
    'form.clearType'(newVal, oldVal) {
      if (newVal && oldVal && newVal != oldVal) {
        this.form.clearDate = null
        this.$nextTick(() => {
          this.$refs.form.clearValidate(['clearDate'])
        })
      }
    }
  },
  mounted() {
    // 页面初始化
    this.initData()
    this.getDateOptions()
  },
  methods: {
    /**
       *  获取数据
       */
    // 获取表单
    initData() {
      this.loading = true
      getAccountRule()
        .then((res) => {
          // 充值赠送余额转成数组
          res.data.defaultAmount =
              res.data.defaultAmount === ''
                ? []
                : res.data.defaultAmount.split(',')
          this.isEnableRecharge = res.data.enableRecharge
          this.isEnableMinAmount = res.data.minAmount !== 0
          res.data.minAmount = res.data.minAmount / 100
          if (!res.data.givenClear) {
            res.data.clearType = 0
            res.data.clearDate = null
          } else if (res.data.clearType === 1) {
            res.data.clearDate = res.data.clearDate.split('-')
          }
          res.data.usedScopes = res.data.usedScopes==null||!res.data.usedScopes?[]:res.data.usedScopes
          this.form = res.data
        })
        .finally(() => {
          this.loading = false
        })
    },

    // 获取筛选
    getDateOptions() {
      // 获取月日选项
      this.day.forEach((v, i) => {
        // 如果i是小于10 补0
        if (i + 1 < 10) {
          var month = '0' + (i + 1)
        } else {
          var month = i + 1
        }
        this.clearDateYearOptions.push({
          value: `${month}`,
          label: `${i + 1}月`,
          children: []
        })
        for (let d = 1; d <= v; d++) {
          // 如果d是小于10 补0
          if (d < 10) {
            var day = '0' + d
          } else {
            var day = d
          }
          this.clearDateYearOptions[i].children.push({
            value: `${day}`,
            label: `${d}号`
          })
        }
      })
    },

    /**
       *  按钮组
       */
    // 保存新配置
    onSubmit(formName) {
      if (!this.form.enableRecharge) {
        const params = { enableRecharge: this.form.enableRecharge }
        this.updateRule(params)
      } else if (!this.minAmountTips && !this.rechargeTips && !this.lockTips) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            const params = JSON.parse(JSON.stringify(this.form))
            if (this.isEnableMinAmount) {
              params.minAmount = this.$math.mul(params.minAmount, 100, 0)
            } else {
              params.minAmount = 0
            }
            if (params.payRule === 2) params.payBalancePercent = 100
            if (params.payRule === 3) params.payBalancePercent = 0
            params.defaultAmount =
                params.defaultAmount === [] ? '' : params.defaultAmount.join(',')
            if (params.clearType === 0) {
              params.givenClear = false
              params.clearType = null
              params.clearDate = null
            } else {
              params.givenClear = true
              if (params.clearType === 1) {
                params.clearDate = params.clearDate.join('-')
              }
            }
            this.updateRule(params)
          }
        })
      }
    },

    // 更新规则
    updateRule(params) {
      this.loading = true
      updateAccountRule(params)
        .then((res) => {
          this.$notify({
            title: '成功',
            message: '更新成功',
            type: 'success',
            duration: 2000,
            offset: 40
          })
        })
        .finally(() => {
          this.loading = false
        })
    },

    // 增加可赠送金额
    addGiveBalance() {
      this.$prompt('', '增加可选储值金额(元)', {
        confirmButtonText: '保存',
        cancelButtonText: '取消',
        inputPattern: new RegExp(
          `^(([1-9]\\d{0,4})|(0\\.(0[1-9]|[1-9][0-9]{0,1}))|([1-9]\\d{0,4}\\.\\d{1,2}))$`
        ),
        inputErrorMessage: '请输入0.01~9999.99范围金额'
      })
        .then(({ value }) => {
          this.form.defaultAmount.push(this.$math.mul(value, 100, 0))
          // 去重
          this.form.defaultAmount = [...new Set(this.form.defaultAmount)]
          // 从小到大排序
          this.form.defaultAmount.sort(function(a, b) {
            return a - b
          })
        })
        .catch((err) => {})
    },

    // 删除可选储值金额
    delDefaultAccount(index) {
      this.form.defaultAmount.splice(index, 1)
    },

    // 打开冻结配置
    openDialogLockRule() {
      this.$refs.dialogLockRule.open()
    },

    // 打开免密金额
    openDialogSkipPasswordAmount() {
      this.$prompt('', '设置小额免密金额(元)', {
        confirmButtonText: '保存',
        cancelButtonText: '取消',
        inputPattern: /^(([1-9][0-9]*)|(0\.(0[1-9]|[1-9][0-9]{0,1}))|([1-9][0-9]*\.\d{1,2})|([0]))$/,
        inputErrorMessage: '请输入正整数，0，正小数（小数位不超过2位）'
      })
        .then(({ value }) => {
          this.form.skipPasswordAmount = this.$math.mul(value, 100, 0)
        })
        .catch((err) => {})
    },

    // 打开修改密码弹框
    openDialogRechargePsw() {
      this.$refs.dialogRechargePsw.open()
    },

    // 打开扣款配置
    openDialogPayRule() {
      this.$refs.dialogPayRule.open()
    },

    /**
       *  方法
       */
    //  判断默认储值最小金额是否小于最低充值金额
    findIsTrueMinAmount() {
      const minDefaultAmount =
          this.form.defaultAmount.length > 0
            ? Math.min(...this.form.defaultAmount)
            : 0
      const minAmount = this.form.minAmount
        ? this.$math.mul(this.form.minAmount, 100, 0)
        : 0
      if (
        this.form.defaultAmount.length > 0 &&
          this.isEnableMinAmount &&
          minDefaultAmount < minAmount
      ) {
        this.minAmountTips = true
      } else {
        this.minAmountTips = false
      }
    }
  }
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
  .vip-account-config {
    .form {
      margin-top: 24px;
      .default-account-val {
        position: relative;
        display: inline-block;
        height: 30px;
        padding: 0 5px 0 10px;
        margin-right: 10px;
        margin-bottom: 5px;
        border-width: 1px;
        border-style: solid;
        border-radius: 5px;
        line-height: 30px;
        font-size: 14px;
        color: $dark-font-color;
        .el-icon-close {
          cursor: pointer;
        }
      }
    }
    .top-card {
      .recharge-tips {
        height: 22px;
        line-height: 22px;
        font-size: 12px;
      }
      .lock-tips {
        font-size: 14px;
        color: #909399;
      }
    }
    .bottom-card {
      margin: 20px 0;
      .pay-rule {
        li {
          margin-bottom: 10px;
          font-size: 14px;
          color: #909399;
        }
      }
    }
  }
</style>
